package org.sunflower.util.ssh2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;


public class FileManagerByFtp {
	private static String hostname = "";		//服务器ip
	private static String username = "";				//用户名
	private static String password = "";			//登录密码
	/**
	 * FTP上传单个文件测试
	 */
	public static void fileUploadByFtp(Map<String,String> map) {
		if(map==null||!map.containsKey("hostname")||!map.containsKey("username")||!map.containsKey("password")){
		}
		hostname = map.get("hostname");
		username = map.get("username");
		password = map.get("password");
		
		FTPClient ftpClient = new FTPClient();
		FileInputStream fis = null;

		try {
			ftpClient.connect(hostname, 22);
			ftpClient.login(username, password);

			File srcFile = new File("C:/Users/Administrator/Desktop/jsPay.jsp");
			fis = new FileInputStream(srcFile);
			// 设置上传目录
			ftpClient.changeWorkingDirectory("/usr/ytu");
			ftpClient.setBufferSize(1024);
			ftpClient.setControlEncoding("GBK");
			// 设置文件类型（二进制）
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftpClient.storeFile("jsPay.jsp", fis);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("FTP客户端出错！", e);
		} finally {
			IOUtils.closeQuietly(fis);
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException("关闭FTP连接发生异常！", e);
			}
		}
	}

	/**
	 * FTP下载单个文件测试
	 */
	public static void fileDownloadByFtp() {
		FTPClient ftpClient = new FTPClient();
		FileOutputStream fos = null;

		try {
			ftpClient.connect("192.85.1.9");
			ftpClient.login("zhangzhenmin", "62672000");

			String remoteFileName = "/home/zhangzhenmin/test_back_081901.sql";
			// fos = new FileOutputStream("E:/test/test_back_081901.sql");
			fos = new FileOutputStream("H:/test/test_back_081901.sql");
			ftpClient.setBufferSize(1024);
			// 设置文件类型（二进制）
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftpClient.retrieveFile(remoteFileName, fos);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("FTP客户端出错！", e);
		} finally {
			IOUtils.closeQuietly(fos);
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException("关闭FTP连接发生异常！", e);
			}
		}
	}
	
	public static void main(String[] args) {
		String hostname = "192.168.1.232";		//服务器ip
		String username = "root";				//用户名
		String password = "hjzx123";			//登录密码
		Map<String,String> map = new HashMap<String,String>();
		map.put("hostname", hostname);
		map.put("username", username);
		map.put("password", password);
		fileUploadByFtp(map);
		//fileDownloadByFtp();
	}
}

